package com.clt.ess.gjzw.utils;

//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class BeanUtils {

//    private static final Logger logger = LoggerFactory.getLogger(BeanUtils.class);

    /**
     * @describe 判断对象所有属性是否有空属性值
     * @returnType boolean true:有为空的属性 false:对象所有属性值都不为空
     * @createTime 2018年3月29日 上午11:38:55
     */
    public static boolean checkFieldValueNull(Object bean) {
        boolean result = true;
        if (bean == null) {
            return true;
        }
        Class<?> cls = bean.getClass();
        Method[] methods = cls.getMethods();
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            try {
                String fieldGetName = parGetName(field.getName());
                //String fieldGetName = field.getName();
                if (!checkGetMet(methods, fieldGetName)) {
                    continue;
                }
                Method fieldGetMet = cls.getMethod(fieldGetName, new Class[]{});
                Object fieldVal = fieldGetMet.invoke(bean, new Object[]{});
                if (fieldVal != null) {
                    if ("".equals(fieldVal)) {
                        //logger.error("后台服务异常终止:" , e);
//                        logger.info("对象属性" + field.getName() + "为必填项！");
                        result = true;
                        return result;
                    } else {
                        result = false;
                    }
                }
            } catch (Exception e) {
                continue;
            }
        }
        return result;
    }

    /**
     * 拼接某属性的 get方法
     *
     * @param fieldName
     * @return String
     */
    public static String parGetName(String fieldName) {
        if (null == fieldName || "".equals(fieldName)) {
            return null;
        }
        int startIndex = 0;
        if (fieldName.charAt(0) == '_') {
            startIndex = 1;
        }

        char chr = fieldName.charAt(1);
        if (Character.isUpperCase(chr)) {
            return "get"
                    + fieldName.substring(startIndex, startIndex + 1)
                    + fieldName.substring(startIndex + 1);
        } else {
            return "get"
                    + fieldName.substring(startIndex, startIndex + 1).toUpperCase()
                    + fieldName.substring(startIndex + 1);
        }

    }

    /**
     * 判断是否存在某属性的 get方法
     *
     * @param methods
     * @param fieldGetMet
     * @return boolean
     */
    public static boolean checkGetMet(Method[] methods, String fieldGetMet) {
        for (Method met : methods) {
            if (fieldGetMet.equals(met.getName())) {
                return true;
            }
        }
        return false;
    }


}
